import { regionArea, queryAllAddress, getCityEstateList, houseListGet, getBaseDetail, getPrizeWayDetail, getPrizeSetDetail, getHighSetDetail, getDiscity, addParams, editParams, getProductInto, luckDrawNumConfig } from './gameParamsTabServ.js'
// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
// import { message } from 'antd'
import { message as msg } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, get, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'

const defultState = {
    gameActivityId: '', //活动Id
    gameActivityTypeId: '', //游戏类型Id
    gameType: '0', // 默认老虎机
    loading: false,
    btnLoading: false, //判断是否提交中状态
    isPromotePro: true, //是否推广项目的选择状态
    actionType: 'add', //判断入口是新增还是修改
    areaList: [], //省市区列表
    estateList: [], //市对应的楼盘项目
    isSubmit: true, //保存按钮的状态
    tabKey: '1', //tab页key
    // currentItem:"",//临时保存礼品或优惠券所选中的key值
    // counselorCurrentItem:"",//临时保存兑奖人员所选中的key值
    city: [],
    clique: '',
    discityList: [],
    areaList1: [],
    query: {
        provinceCodes: [],
        cityCodes: [],
        wholeCountry: false,
    },
    gameBaseDetail: {
        projectId: "", //项目ID
        productId: "", //楼盘ID
        promoteStatus: true, //推广模式
        startTime: moment().format('YYYY-MM-DD 00:00:01'), //开始时间
        endTime: moment().add(1, "months").format('YYYY-MM-DD 23:59:59'), //结束时间
        virtualNumber: 0, //参与人数
        projectName: '', //项目名称
        launchApp: "1", //投放程序；1:美的置业云;2:智美秀
        gameActivityId: "",
        cityCodes: [],
        provinceCodes: [],
        titleImgUrl: "", //游戏界面头部标题
    },
    gameBaseImgModal: {
        visible: false,
        srcs: [],
    },

    gamePrizeWayDetail: {
        startSubscriptionTime: '', //客户认购开始时间
        endSubscriptionTime: '', //客户认购结束时间
        startMarketingTime: '', //推介开始时间
        endMarketingTime: '', //推介结束时间
        // expectedNumber:0,//预计参与人数
        winningRate: "", //总中奖概率
        winningTimesPerPerson: 0, //中奖次数
        participators: "0", //参与人群类型
        luckDrawTimesMax: 0, //每人总抽奖次数
        luckDrawTimesInit: 0, //每人初始抽奖次数
    },
    prizeTabIndex: '1', //奖项tab页下标
    panes: [], //奖项几等奖列表
    gamePrizeSetDetailList: [], //奖项设置列表
    selectItem: [],
    //全选按钮
    indeterminate: false,
    checkAll: false,
    projectData: {
        province: '', //省
        city: '', //市
        productIds: [], //楼盘id
    },
    mapAddress: "", //临时的楼盘地址
    gamePrizeSetDetail: {
        awardType: "0", //奖项类型0为自定义1为商城礼品2为优惠券
        awardName: "", //自定义的奖品名称
        awardNumber: "", //奖品总库存
        useNumber: 0, //已用数量
        awardStock: 0, //奖品剩余库存
        awardImgUrl: "", //自定义奖项图片
        winningRate: "100", //此奖项在总奖品中奖概率
        duration: "", //固定兑奖时间
        durationType: "1", //固定兑奖时间类型
        awardGamePlayerType: "1", //奖项玩家类型
        outerId: "", //优惠券ID或礼品ID
        operationHint: "", //操作提示/兑奖提示
        rewardWay: "1", //兑奖方式
        noPrizeImgUrls: "", //未中奖图片数组url
        prizeImgUrls: "", //中奖图片数组url
        startTime: "", //兑奖截止开始时间
        endTime: "", //兑奖截止结束时间
        estateAddress: [], //楼盘地址
        giftName: "", //礼品名称
        awardLevel: "1", //奖项等级
        consolationAward: "0", //是否为安慰奖0否1是
        redeemUserNames: "", //选中的兑奖人员名称
        counselors: [], //兑奖人员ID
        gameActivityAwardId: "", //奖项设置ID（修改的时候一定要传值）
        currentItem: [],
        biz: [],
        counselorBiz: [],
        redAmount: '', // 红包金额
        sendRedAccount: '', // 红包发放账户
        points: '', // 发放积分
    },
    gamePrizeSetImgModal: {
        visible: false,
        srcs: [],
    },
    // biz: {
    //  rowSelection_type:'radio',
    //  selectedRowKeys:[]
    // },
    // counselorBiz: {
    //  rowSelection_type:'checkbox',
    //  selectedRowKeys:[]
    // },
    giftModalObj: {
        giftVisible: false, //礼品选择框显示隐藏
        discountCouponVisible: false, //优惠券选择框显示隐藏
        giftInfo: {}, //选中礼品对象
        discountCouponInfo: {} //选中优惠券对象
    },
    counselorModalObj: {
        counselorVisible: false, //兑奖人员选择框显示隐藏
        counselorInfos: [] //选中人员数组
    },

    gameHighSetDetail: {
        helpInvitation: '好友{name}急需您的助力，请为ta助力', //助力邀请语
        allowSharing: '0', //是否开启分享好友状态
        assistanceForce: '', //助力人数
        assistedOpening: '0', //是否开启好友助力状态 
        gameActivityId: '', //游戏活动id
        sharingImgUrl: '', //分享好友图片
        sharingPosterShow: '0', //是否开启分享海报状态
        sharingTitle: '', //分享标题
        sponsorUnit: '', //主办单位
        posterImgUrl: '', //分享海报图片
    },
    gameHighSetImgModal: {
        visible: false,
        srcs: [],
    },
    gameLuckDrawNumConfig: [],
    rewardRange: [],
    dailyLogins: [],
    developAgents: [],
    onlineBuy: [],
    dailyLoginChecked: false,
    developAgentChecked: false,
    onlineBuyChecked: false,
    gameStatus: '',
    area1: [],
    areas: [],
    roleType: 1
}

// 声明module
const tmpModule = {
    namespace: 'gameParamsTabModel',
    state: cloneDeep(defultState),
    subscriptions: {
        setup({ dispatch, history }) {
            let clique = localStorage.getItem('clique');
            history.listen((location) => {
                let { pathname, query } = location;
                // 页面路由匹配时执行
                if ('' + tmpModule.pathname === '' + pathname) {
                    dispatch({ type: 'updateStore', payload: cloneDeep(defultState) })
                    dispatch({ type: 'updateStore', payload: { gameStatus: query.gameStatus, gameActivityId: query.gameActivityId, gameActivityTypeId: query.gameActivityTypeId, gameType: query.gameType, actionType: query.actionType, clique: localStorage.getItem('clique') } })
                    dispatch({ type: 'getAreaList', payload: {} });
                    dispatch({ type: 'regionArea', payload: {} });
                    dispatch({ type: 'getCityEstateList', payload: { params: { province: '', city: '' } } })
                    if (!!get(query, 'gameActivityId', '')) {
                        dispatch({ type: 'app/setTabTitle', payload: { title: '编辑游戏设置', location } });
                        // dispatch({ type: 'getDetail', payload: {  gameActivityId: query.gameActivityId} });
                        // dispatch({ type: 'getPrizeWayDetail', payload: {  gameActivityId: query.gameActivityId} })
                        // dispatch({ type: 'getPrizeSetDetail', payload: {  gameActivityId: query.gameActivityId} })
                        // dispatch({ type: 'getHighSetDetail', payload: {  gameActivityId: query.gameActivityId} })
                        dispatch({ type: 'getLuckDrawNumConfig', payload: { pageNo: 1, pageSize: 20, gameActivityId: query.gameActivityId } })
                    } else {
                        dispatch({ type: 'app/setTabTitle', payload: { title: '新增游戏设置', location } });
                    }
                }
            })
        },


        // setup({ dispatch, history }) {
        //     history.listen(({ pathname, query }) => {
        //         if ('' + tmpModule.pathname === '' + pathname) {
        //             //   dispatch({type: 'queryInfo', payload: {}}) // end dispatch
        //             dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
        //         }
        //     })
        // },
    },

    // 方法列表
    effects: {
        // 所属区域
        * regionArea({ payload }, { put, call, select }) {
            let { gameBaseDetail, areas } = yield select(state => state[tmpModule.namespace])
            const { success, data } = yield call(regionArea)
            if (success) {
                if (gameBaseDetail.regionId) {
                    data.map((item, index) => {
                        if (item.value == gameBaseDetail.regionId) {
                            areas = makeAddress(item.children, 2)
                            areas.shift()
                        }
                    })
                    yield put({
                        type: 'getProduct',
                        payload: {}
                    })
                }
                console.log('aaaa', data)
                yield put({ type: 'updateStore', payload: { area1: data, areas } })
            }
        },
        // 查询记录
        * getDetail({ payload }, { put, call, select }) {
            try {
                let { gameBaseDetail, query, city, areaList1, gameActivityId } = yield select(state => state[tmpModule.namespace])
                const { result, success, message } = yield call(getBaseDetail, payload)
                if (success) {
                    if (result) {
                        // query.cityCodes = [["130100","130300","130400"]];
                        // query.provinceCodes = ['130000'];
                        // let launchApp=[];
                        if (!result.gameActivityId || result.gameActivityId == "") {
                            result.gameActivityId = gameActivityId;
                        }
                        // if(result.launchApp.length > 0){
                        //  launchApp = result.launchApp.split(",");
                        //  if(launchApp.length > 0){
                        //      for(let i=0,len=launchApp.length;i<len;i++){
                        //          if(launchApp[i] == ""){
                        //              launchApp.splice(i,1);
                        //              len--;
                        //              --i;
                        //          }
                        //      }
                        //  }
                        // }
                        if (result.type && result.type != "" && result.type == "1") {
                            result.promoteStatus = true;
                            result.province = result.provinceCode;
                            result.city = result.cityCode;
                        } else {
                            result.promoteStatus = false;
                        }
                        query.cityCodes = result.cityCodes && result.cityCodes.length > 0 ? result.cityCodes : [];
                        query.provinceCodes = result.provinceCodes && result.provinceCodes.length > 0 ? result.provinceCodes : [];
                        // result.launchApp = launchApp;
                        if (query.provinceCodes.length > 0) {
                            if (query.provinceCodes.length == 1 && query.provinceCodes[0] == "0") {
                                query.provinceCodes = ['0']
                                query.cityCodes = []
                            } else {
                                for (var i = 0; i < query.provinceCodes.length; i++) {
                                    // console.log(query.provinceCodes[i])
                                    // if(roleArea.indexOf(query.provinceCodes[i])==-1){
                                    // delete query.provinceCodes[i]
                                    // }
                                    for (var y = 0; y < areaList1.length; y++) {
                                        // console.log(areaList1[y])
                                        if (query.provinceCodes[i] == areaList1[y].value) {
                                            city[i] = areaList1[y].children
                                                // console.log(areaList1[y])
                                        }
                                    }
                                    city.map(item => {
                                        item.map(child => {
                                            child.disabled = true;
                                        })
                                    })
                                }
                            }
                        }
                        if (result.cityCode && result.cityCode != "") {
                            yield put({ type: 'getHouseArea', payload: { query: query, province: result.provinceCode, city: result.cityCode } })
                        }
                    }
                    yield put({ type: 'updateStore', payload: { gameBaseDetail: result } })

                }
            } catch (e) {}
        },

        // 查询记录
        * getPrizeWayDetail({ payload }, { put, call, select }) {
            try {
                let { gamePrizeWayDetail } = yield select(state => state[tmpModule.namespace])
                const { result, success, message } = yield call(getPrizeWayDetail, payload)
                if (success) {
                    if (result) {
                        result.participators = result.participators && result.participators != null ? result.participators + '' : '0';
                        if (result.participators == "1" || result.participators == "3") {
                            result.startSubscriptionTime = result.startTime;
                            result.endSubscriptionTime = result.endTime;
                        } else if (result.participators == "4") {
                            result.startMarketingTime = result.startTime;
                            result.endMarketingTime = result.endTime;
                        }
                        let winningRate = result.winningRate;
                        result.winningRate = Number(winningRate) / 100;
                        yield put({ type: 'updateStore', payload: { gamePrizeWayDetail: result } })
                    }

                }
            } catch (e) {}
        },

        // 查询记录
        * getPrizeSetDetail({ payload }, { put, call, select }) {
            try {
                let { gamePrizeSetDetail, gamePrizeSetDetailList, panes, gameBaseDetail, mapAddress, prizeTabIndex } = yield select(state => state[tmpModule.namespace])
                const { result, success, message } = yield call(getPrizeSetDetail, payload)
                if (success) {

                    if (result && result.length > 0) {
                        panes = [];
                        for (let i = 0; i < result.length; i++) {
                            let re = result[i];
                            let awardType = re.awardType + '';
                            re.winningRate = re.winningRate ? Number(re.winningRate) / 100 : 0;
                            re.awardType = awardType && awardType != null && awardType != 'null' ? re.awardType + '' : '0';
                            re.durationType = re.durationType && re.durationType != null ? re.durationType + '' : '1';
                            re.awardGamePlayerType = re.awardGamePlayerType && re.awardGamePlayerType != null ? re.awardGamePlayerType + '' : '1';
                            re.rewardWay = re.rewardWay && re.rewardWay != null ? re.rewardWay + '' : '1';
                            re.awardLevel = re.awardLevel && re.awardLevel != null ? re.awardLevel + '' : '1';
                            re.consolationAward = re.consolationAward && re.consolationAward != null ? re.consolationAward + '' : '0';
                            re.awardStock = re.awardStock && re.awardStock != null ? re.awardStock + '' : '0';
                            re.useNumber = Number(re.awardNumber) - Number(re.awardStock);
                            re.estateAddress = re.estateAddress ? JSON.parse(re.estateAddress) : [];
                            re.outerId = re.outerId && re.outerId != null ? re.outerId : '';
                            re.counselors = re.counselors ? JSON.parse(re.counselors) : [];
                            re.currentItem = [];
                            if (re.outerId && re.outerId != null) {
                                re.currentItem.push(re.outerId);
                            } else {
                                re.currentItem = [];
                            }
                            if (re.counselors.length > 0) {
                                for (let i = 0; i < re.counselors.length; i++) {
                                    re.counselorCurrentItem.push(re.counselors[i].counselorId);
                                }
                            } else {
                                re.counselorCurrentItem = [];
                            }
                            re.biz = {
                                rowSelection_type: 'radio',
                                selectedRowKeys: re.currentItem
                            }
                            re.counselorBiz = {
                                rowSelection_type: 'checkbox',
                                selectedRowKeys: re.counselorCurrentItem
                            }
                            if (re.noPrizeImgUrls && re.noPrizeImgUrls != "") {
                                re.noPrizeImgUrls = JSON.parse(re.noPrizeImgUrls);
                            }
                            if (re.prizeImgUrls && re.prizeImgUrls != "") {
                                re.prizeImgUrls = JSON.parse(re.prizeImgUrls);
                            }
                            if (re.counselors && re.counselors.length > 0) {
                                re.redeemUserNames = "";
                                for (let i = 0; i < re.counselors.length; i++) {
                                    if (i > 0) {
                                        re.redeemUserNames += ",";
                                    }
                                    re.redeemUserNames += re.counselors[i].counselorName;
                                }
                            }
                            if (gamePrizeSetDetailList.length > 0) {
                                let flag = false;
                                for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                                    if (gamePrizeSetDetailList[i].awardLevel == re.awardLevel) {
                                        flag = true;
                                    }
                                }
                                if (!flag) {
                                    gamePrizeSetDetailList.push(re);
                                }
                            } else {
                                gamePrizeSetDetailList.push(re);
                            }

                            let closable = true;
                            if (result.length <= 1) {
                                closable = false;
                            }
                            panes.push({
                                title: `${re.awardLevel}等奖`,
                                key: re.awardLevel + "",
                                closable: closable
                            });
                            if (gameBaseDetail.promoteStatus && re.estateAddress.length == 1) {
                                mapAddress = re.estateAddress[0].mapAddress;
                            }
                        }
                        yield put({ type: 'updateStore', payload: { mapAddress: mapAddress, gamePrizeSetDetail: result[prizeTabIndex - 1], gamePrizeSetDetailList: gamePrizeSetDetailList, panes: panes } })
                    }
                }
            } catch (e) {}
        },

        * getHighSetDetail({ payload }, { put, call, select }) {
            try {
                let { gameHighSetDetail } = yield select(state => state[tmpModule.namespace])
                const { result, success, message } = yield call(getHighSetDetail, payload)
                if (success) {
                    result.allowSharing = result.allowSharing && result.allowSharing != null ? result.allowSharing + '' : '0';
                    result.assistedOpening = result.assistedOpening && result.assistedOpening != null ? result.assistedOpening + '' : '0';
                    result.sharingPosterShow = result.sharingPosterShow && result.sharingPosterShow != null ? result.sharingPosterShow + '' : '0';
                    yield put({ type: 'updateStore', payload: { gameHighSetDetail: result } })
                }
            } catch (e) {}
        },

        * getAreaList({ payload }, { put, call, select }) {
            try {
                let { gameActivityId, gamePrizeSetDetail, gamePrizeSetDetailList, panes } = yield select(state => state[tmpModule.namespace])
                const { success, data } = yield call(queryAllAddress, {})
                if (success) {
                    //todo: 接口格式调整后删除
                    let areaList = []
                    let areaList1 = []
                    let arr = [data[0]]
                    let attr = [data[data.length - 1]]
                    data[0] = {
                        label: "北京",
                        value: "110100",
                        children: arr
                    }
                    data[data.length - 1] = {
                            label: "澳门",
                            value: "820000",
                            children: attr
                        }
                        //console.log(data,"data")
                        //去掉第三级，
                    areaList = makeAddress(data, 2, false)
                    areaList1 = makeAddress(data, 2)
                    areaList1 = data
                    areaList1.shift()
                    yield put({ type: 'updateStore', payload: { areaList: areaList, areaList1: areaList1 } })

                    if (gameActivityId && gameActivityId != "") {
                        yield put({ type: 'getDetail', payload: { gameActivityId: gameActivityId } });
                        yield put({ type: 'getPrizeWayDetail', payload: { gameActivityId: gameActivityId } });
                        yield put({ type: 'getPrizeSetDetail', payload: { gameActivityId: gameActivityId } });
                        yield put({ type: 'getHighSetDetail', payload: { gameActivityId: gameActivityId } });
                    } else {
                        gamePrizeSetDetail.noPrizeImgUrls = ["https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M1.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M2.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M5.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M6.png"];
                        gamePrizeSetDetail.prizeImgUrls = ["https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M3.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M3.png", "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M3.png"];
                        if (gamePrizeSetDetailList.length > 0) {
                            let flag = false;
                            for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                                if (gamePrizeSetDetailList[i].awardLevel == gamePrizeSetDetail.awardLevel) {
                                    flag = true;
                                }
                            }
                            if (!flag) {
                                gamePrizeSetDetailList.push(gamePrizeSetDetail);
                            }
                        } else {
                            gamePrizeSetDetailList.push(gamePrizeSetDetail);
                        }
                        panes = [{
                            title: `1等奖`,
                            key: "1",
                            closable: false
                        }];
                        yield put({ type: 'updateStore', payload: { panes: panes, gamePrizeSetDetailList: gamePrizeSetDetailList, gamePrizeSetDetail: gamePrizeSetDetail } })
                    }
                }
            } catch (e) {}
        },
        // 获取户型项目
        * getHouseArea({ payload }, { put, call, select }) {
            let params = cloneDeep(payload)
            params.pageNo = 1;
            params.pageSize = 999999;
            params.shelfStatus = 1;
            try {
                const { success, rows } = yield call(houseListGet, params)
                if (success) {
                    yield put({ type: 'updateStore', payload: { estateList: rows || [] } })
                }
            } catch (e) {}
        },
        * getCityEstateList({ payload }, { put, call, select }) {
            try {
                const data = yield call(getCityEstateList, { pageNo: 1, pageSize: 1000, shelfStatus: 1, ...payload.params })
                if (data.success) {
                    let estateList = data.rows
                    estateList && estateList.forEach((e, i) => {
                        e.label = e.name;
                        e.value = e.productId
                    })
                    yield put({ type: 'updateStore', payload: { estateList } });
                }
            } catch (e) {}
        },

        * getDiscity({ payload }, { put, call, select }) {
            let pId = payload.pId;
            let { discityList } = yield select((state) => state[tmpModule.namespace])
            let { success, rows } = yield call(getDiscity, pId)
            if (success) {
                let arr = rows.filter(item => {
                    return !discityList.includes(item.cityCode)
                }).map(item => item.cityCode)
                yield put({ type: 'updateStore', payload: { discityList: [...discityList, ...arr] } })
            }
        },

        //提交表单
        * submit({ payload }, { put, call, select }) {
            try {
                let { query, gameActivityTypeId, tabKey, gameHighSetDetail, gamePrizeWayDetail, gamePrizeSetDetailList, gameBaseDetail, actionType, estateList, developAgents, dailyLogins, onlineBuy, rewardRange, gameLuckDrawNumConfig, gameType, dailyLoginChecked, developAgentChecked, onlineBuyChecked } = yield select((state) => state[tmpModule.namespace])

                //校验基础设置表单数据
                if (gameBaseDetail.endTime == "") {
                    tabKey = "1";
                    msg.error('请选择活动时间！');
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gameBaseDetail.title == "") {
                    tabKey = "1";
                    msg.error('请输入活动标题！');
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gameBaseDetail.launchApp == "") {
                    tabKey = "1";
                    msg.error('请选择投放程序');
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gameBaseDetail.promoteStatus) {
                    if (!gameBaseDetail.productId || gameBaseDetail.productId == "") {
                        msg.error('所属项目不能为空！');
                        tabKey = "1";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                } else {
                    if (query.provinceCodes.length == 0) {
                        msg.error('请选择活动范围！');
                        tabKey = "1";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }

                //校验派奖方式的数据
                if (gamePrizeWayDetail.participators == "") {
                    msg.error('请选择参与人群！');
                    tabKey = "2";
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gamePrizeWayDetail.participators == "1" || gamePrizeWayDetail.participators == "3") {
                    if (gamePrizeWayDetail.endSubscriptionTime == "") {
                        msg.error('请选择客户认购限期！');
                        tabKey = "2";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }
                if (gamePrizeWayDetail.participators == "4") {
                    if (gamePrizeWayDetail.endMarketingTime == "") {
                        msg.error('请选择推介限期！');
                        tabKey = "2";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }
                if (gamePrizeWayDetail.winningTimesPerPerson == "") {
                    msg.error('请输入每人最多可中奖次数！');
                    tabKey = "2";
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gamePrizeWayDetail.winningRate == "") {
                    msg.error('请输入总中奖概率！');
                    tabKey = "2";
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }

                //校验奖项设置数据
                if (gamePrizeSetDetailList.length > 0) {
                    let totalWinningRate = 0
                    let consolationAwardNum = []
                    for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                        let gamePrizeSetDetail = gamePrizeSetDetailList[i];
                        let gamePrizeIndex = i + 1
                        totalWinningRate = totalWinningRate + Math.round(Number(gamePrizeSetDetail.winningRate) * 100)
                        if (gamePrizeSetDetail.consolationAward == 0) {
                            consolationAwardNum.push(gamePrizeSetDetail.consolationAward)
                        }
                        if (!gamePrizeSetDetail.prizeImgUrls || gamePrizeSetDetail.prizeImgUrls.length == 0) {
                            msg.error(`${gamePrizeIndex}等奖，请上传中奖标志的小图标`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        } else {
                            if (gamePrizeSetDetail.prizeImgUrls.length < 3) {
                                msg.error(`${gamePrizeIndex}等奖，请上传至少三张中奖标志的小图标。`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        if (!gamePrizeSetDetail.noPrizeImgUrls || gamePrizeSetDetail.noPrizeImgUrls.length == 0) {
                            msg.error(`${gamePrizeIndex}等奖，请上传未中奖标志的小图标。`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        } else {
                            if (gamePrizeSetDetail.noPrizeImgUrls.length < 3) {
                                msg.error(`${gamePrizeIndex}等奖，请上传至少三张未中奖标志的小图标。`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        if (gamePrizeSetDetail.awardType == "") {
                            msg.error(`${gamePrizeIndex}等奖，请选择奖项类型！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        if (gamePrizeSetDetail.awardType == "1") {
                            if (!gamePrizeSetDetail.giftName || gamePrizeSetDetail.giftName == "") {
                                msg.error(`${gamePrizeIndex}等奖，请选择礼品！`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        } else if (gamePrizeSetDetail.awardType == "2") {
                            if (!gamePrizeSetDetail.giftName || gamePrizeSetDetail.giftName == "") {
                                msg.error(`${gamePrizeIndex}等奖，请选择优惠券！`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        if (gamePrizeSetDetail.awardName == "") {
                            msg.error(`${gamePrizeIndex}等奖，请输入奖品名称！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        if (gamePrizeSetDetail.awardImgUrl == "") {
                            msg.error(`${gamePrizeIndex}等奖，请上传奖品小图！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        if (gamePrizeSetDetail.awardNumber == "") {
                            msg.error(`${gamePrizeIndex}等奖，请输入奖品数量！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        } else {
                            if (Number(gamePrizeSetDetail.awardNumber) < Number(gamePrizeSetDetail.useNumber)) {
                                msg.error("总库存不能少于已用数量:" + gamePrizeSetDetail.useNumber);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            } else if (Number(gamePrizeSetDetail.awardNumber) < Number(gamePrizeSetDetail.awardStock)) {
                                msg.error("总库存不能少于剩余库存");
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        // else if(gamePrizeSetDetail.winningRate == ""){
                        //  message.error('请输入中奖概率！');
                        //  tabKey = "3";
                        //  yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        //  return false;
                        // }
                        if (gamePrizeSetDetail.awardGamePlayerType == "") {
                            msg.error(`${gamePrizeIndex}等奖，请选择指定中奖人群！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        if (gamePrizeSetDetail.rewardWay == "") {
                            msg.error(`${gamePrizeIndex}等奖，请选择兑奖方式！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        } else if (gamePrizeSetDetail.rewardWay == "1") {
                            if (gamePrizeSetDetail.estateAddress.length == 0) {
                                msg.error(`${gamePrizeIndex}等奖，请选择兑奖项目！`);
                                tabKey = "3";
                                prizeTabIndex = i + 1;
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey, prizeTabIndex: prizeTabIndex } });
                                return false;
                            }
                        } else if (gamePrizeSetDetail.rewardWay == "3") {
                            if (!gamePrizeSetDetail.counselors || gamePrizeSetDetail.counselors.length == 0) {
                                msg.error(`${gamePrizeIndex}等奖，请选择兑奖人员！`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        if (gamePrizeSetDetail.operationHint == "") {
                            msg.error(`${gamePrizeIndex}等奖，请输入兑奖提示，最多20个字！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        // if(gamePrizeSetDetail.estateAddress == "" && gamePrizeSetDetail.rewardWay == "1"){
                        //  msg.error('请输入楼盘地址！');
                        //  tabKey = "3";
                        //  yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        //  return false;
                        // }
                        if (gamePrizeSetDetail.durationType == "" && gamePrizeSetDetail.rewardWay != "2") {
                            msg.error(`${gamePrizeIndex}等奖，请选择兑奖期限方式！`);
                            tabKey = "3";
                            yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                            return false;
                        }
                        if (gamePrizeSetDetail.durationType == "1" && gamePrizeSetDetail.rewardWay == "1") {
                            if (gamePrizeSetDetail.endTime == "") {
                                msg.error(`${gamePrizeIndex}等奖，请选择兑奖限期！`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                        if (gamePrizeSetDetail.durationType == "2" && gamePrizeSetDetail.rewardWay != "2") {
                            if (gamePrizeSetDetail.duration == "") {
                                msg.error(`${gamePrizeIndex}等奖，请选择兑奖日期！`);
                                tabKey = "3";
                                yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                                return false;
                            }
                        }
                    }
                    if (consolationAwardNum.length == gamePrizeSetDetailList.length && gameType == '1') {
                        msg.error('至少设置其中一个奖项为安慰奖');
                        return false;
                    }
                    if (totalWinningRate != 10000) {
                        msg.error('所有奖项概率之和不等于100%');
                        return false;
                    }
                } else {
                    msg.error('请填写奖项设置信息');
                    return false;
                }


                //校验高级设置数据
                if (gameHighSetDetail.sponsorUnit == "") {
                    msg.error('请输入主办单位！');
                    tabKey = "4";
                    yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                    return false;
                }
                if (gameHighSetDetail.allowSharing == "1") {
                    if (gameHighSetDetail.sharingTitle == "") {
                        msg.error('请输入分享标题！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    } else if (gameHighSetDetail.sharingImgUrl == "") {
                        msg.error('请上传分享好友图片！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }
                if (gameHighSetDetail.sharingPosterShow == "1") {
                    if (gameHighSetDetail.posterImgUrl == "") {
                        msg.error('请上传分享海报图片！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }
                if (gameHighSetDetail.assistedOpening == "1") {
                    let res = /^[1-9]\d*$/;
                    if (gameHighSetDetail.assistanceForce == "") {
                        msg.error('请输入助力人数！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    } else if (!res.test(gameHighSetDetail.assistanceForce)) {
                        msg.error('请输入整数！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                    if (gameHighSetDetail.helpInvitation == "") {
                        msg.error('请输入助力邀请语,最多40个字！');
                        tabKey = "4";
                        yield put({ type: 'updateStore', payload: { tabKey: tabKey } });
                        return false;
                    }
                }
                yield put({ type: 'updateStore', payload: { btnLoading: true } });
                let allParams = {};

                //---------抽奖次数增加配置---------
                let luckDrawNumConfig = []
                if (dailyLogins.length > 0 && dailyLoginChecked) {
                    let daily = []
                    dailyLogins.map(item => {
                        daily.push((rewardRange.indexOf(item) + 1))
                    })

                    let login = {
                        id: '',
                        type: '1',
                        incrNum: 1,
                        awardLevel: daily.toString(),
                        remark: '每日首次登陆'
                    }
                    if (typeof(gameLuckDrawNumConfig[0]) != 'undefined') {
                        login.id = gameLuckDrawNumConfig[0].id ? gameLuckDrawNumConfig[0].id : ''
                    }

                    luckDrawNumConfig.push(login)
                }


                if (developAgents.length > 0 && developAgentChecked) {
                    let agents = []
                    developAgents.map(item => {
                        agents.push((rewardRange.indexOf(item) + 1))
                    })

                    let develop = {
                        id: '',
                        type: '2',
                        incrNum: 1,
                        awardLevel: agents.toString(),
                        remark: '活动期间发展经济人'
                    }
                    if (typeof(gameLuckDrawNumConfig[1]) != 'undefined') {
                        develop.id = gameLuckDrawNumConfig[1] ? gameLuckDrawNumConfig[1].id : ''
                    }

                    luckDrawNumConfig.push(develop)
                }



                if (onlineBuy.length > 0 && onlineBuyChecked) {
                    let buys = []
                    onlineBuy.map(item => {
                        buys.push((rewardRange.indexOf(item) + 1))
                    })
                    let onlineshop = {
                        id: '',
                        type: '3',
                        incrNum: 1,
                        awardLevel: buys.toString(),
                        remark: '活动期间在线认购'
                    }
                    if (typeof(gameLuckDrawNumConfig[2]) != 'undefined') {
                        onlineshop.id = gameLuckDrawNumConfig[2].id ? gameLuckDrawNumConfig[2].id : ''
                    }
                    luckDrawNumConfig.push(onlineshop)
                }


                allParams.luckDrawNumConfig = luckDrawNumConfig;
                //---------抽奖次数增加配置---------

                //组装基础设置数据
                gameBaseDetail.gameActivityTypeId = gameActivityTypeId;

                if (gameBaseDetail.productId && gameBaseDetail.productId != "") {
                    for (let i = 0; i < estateList.length; i++) {
                        if (estateList[i].productId == gameBaseDetail.productId) {
                            gameBaseDetail.projectName = estateList[i].name;
                            break;
                        }
                    }
                }
                // if(gameBaseDetail.launchApp.length > 0){
                //  let launchApp = "";
                //  for(let i=0;i<gameBaseDetail.launchApp.length;i++){
                //      if(gameBaseDetail.launchApp[i] != ","){
                //          if(i > 0){
                //              launchApp += ",";
                //          }
                //          launchApp += gameBaseDetail.launchApp[i];
                //      }
                //  }
                //  gameBaseDetail.launchApp = launchApp;
                // }
                if (gameBaseDetail.promoteStatus) {
                    gameBaseDetail.type = 1;
                    gameBaseDetail.cityCode = gameBaseDetail.city;
                    gameBaseDetail.provinceCode = gameBaseDetail.province;
                    // if(query.provinceCodes.length > 0){
                    //  if(query.provinceCodes[0] == "0"){
                    //      gameBaseDetail.type = 3;
                    //  }else{
                    //      gameBaseDetail.provinceCodes = query.provinceCodes;
                    //      gameBaseDetail.cityCodes = query.cityCodes;
                    //  }
                    // }
                } else {
                    gameBaseDetail.type = 2;
                    // if(query.provinceCodes.length > 0){
                    //  if(query.provinceCodes[0] == "0"){
                    //      gameBaseDetail.type = 3;
                    //  }else{
                    //      gameBaseDetail.provinceCodes = query.provinceCodes;
                    //      gameBaseDetail.cityCodes = query.cityCodes;
                    //  }
                    // }
                    gameBaseDetail.provinceCode = '';
                    gameBaseDetail.cityCode = '';
                }
                if (query.provinceCodes.length > 0) {
                    gameBaseDetail.provinceCodes = query.provinceCodes;
                    gameBaseDetail.cityCodes = query.cityCodes;
                    if (query.provinceCodes[0] === "0") {
                        gameBaseDetail.cityCodes = [
                            ['0']
                        ];
                        //gameBaseDetail.provinceCode = '0';
                        // gameBaseDetail.cityCode ='0';
                    }
                }
                yield put({ type: 'updateStore', payload: { gameBaseDetail: gameBaseDetail } });
                allParams.basicOption = gameBaseDetail;

                //组装派奖方式数据
                if (gamePrizeWayDetail.participators == "1" || gamePrizeWayDetail.participators == "3") {
                    gamePrizeWayDetail.startTime = gamePrizeWayDetail.startSubscriptionTime;
                    gamePrizeWayDetail.endTime = gamePrizeWayDetail.endSubscriptionTime;
                } else if (gamePrizeWayDetail.participators == "4") {
                    gamePrizeWayDetail.startTime = gamePrizeWayDetail.startMarketingTime;
                    gamePrizeWayDetail.endTime = gamePrizeWayDetail.endMarketingTime;
                }
                let winningRate = gamePrizeWayDetail.winningRate;
                gamePrizeWayDetail.winningRate = Math.round(Number(winningRate) * 100);
                yield put({ type: 'updateStore', payload: { gamePrizeWayDetail: gamePrizeWayDetail } });
                allParams.awardMode = gamePrizeWayDetail;
                // gamePrizeSetDetail.awardStock = Number(gamePrizeSetDetail.awardNumber)-Number(gamePrizeSetDetail.useNumber);

                let gamePrizeSetList = [];
                if (gamePrizeSetDetailList.length > 0) {

                    for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                        gamePrizeSetDetailList[i].winningRate = gamePrizeSetDetailList[i].winningRate == null || gamePrizeSetDetailList[i].winningRate == "" ? 0 : Math.round(Number(gamePrizeSetDetailList[i].winningRate) * 100);
                        let prizeSetData = gamePrizeSetDetailList[i];

                        prizeSetData.sort = i;
                        //组合中奖图片
                        prizeSetData.prizeImgUrls = JSON.stringify(prizeSetData.prizeImgUrls);
                        //组合未中奖图片
                        prizeSetData.noPrizeImgUrls = JSON.stringify(prizeSetData.noPrizeImgUrls);
                        prizeSetData.estateAddress = JSON.stringify(prizeSetData.estateAddress);
                        gamePrizeSetList.push(prizeSetData);
                    }
                }
                //组装奖项设置数据
                allParams.awardList = gamePrizeSetList;

                //组装高级设置数据
                allParams.advancedSetting = gameHighSetDetail;
                //console.log(JSON.stringify(allParams));
                let server = gameBaseDetail.gameActivityId == '' ? addParams : editParams;
                const { success, result, message } = yield call(server, {...allParams });
                console.log('success res', success)
                if (success) {
                    if (result) {
                        gameBaseDetail.gameActivityId = result.gameActivityId;
                        yield put({ type: 'updateStore', payload: { gameBaseDetail: gameBaseDetail } });
                    }
                    yield put({ type: 'getDetail', payload: { gameActivityId: gameBaseDetail.gameActivityId } });
                    yield put({ type: 'getPrizeWayDetail', payload: { gameActivityId: gameBaseDetail.gameActivityId } });
                    yield put({ type: 'getPrizeSetDetail', payload: { gameActivityId: gameBaseDetail.gameActivityId } });
                    yield put({ type: 'getHighSetDetail', payload: { gameActivityId: gameBaseDetail.gameActivityId } });
                    // 抽奖次数配置
                    yield put({ type: 'getLuckDrawNumConfig', payload: { gameActivityId: gameBaseDetail.gameActivityId } })
                    yield put({ type: 'updateStore', payload: { btnLoading: false } })
                    msg.success('保存活动详情设置成功');
                } else {
                    yield put({ type: 'updateStore', payload: { btnLoading: false } })
                    msg.error(message);
                }
                gamePrizeWayDetail.winningRate = gamePrizeWayDetail.winningRate / 100;
                for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                    gamePrizeSetDetailList[i].prizeImgUrls = JSON.parse(gamePrizeSetDetailList[i].prizeImgUrls);
                    gamePrizeSetDetailList[i].noPrizeImgUrls = JSON.parse(gamePrizeSetDetailList[i].noPrizeImgUrls);
                    gamePrizeSetDetailList[i].estateAddress = JSON.parse(gamePrizeSetDetailList[i].estateAddress);
                    gamePrizeSetDetailList[i].winningRate = gamePrizeSetDetailList[i].winningRate / 100;
                }
                yield put({ type: 'updateStore', payload: { gamePrizeSetDetailList: gamePrizeSetDetailList, gamePrizeSetDetail: gamePrizeSetDetail, gamePrizeWayDetail: gamePrizeWayDetail } });


            } catch (e) {
                // console.log(e)
            }

        },
        * gameBaseDealEditor({ payload }, { put, select }) {
            let { gameBaseDetail } = yield select(state => state[tmpModule.namespace])
            let newDetail = Object.assign({}, gameBaseDetail)
            newDetail.ruleDesc = payload.ruleDesc
            yield put({ type: 'updateStore', payload: { gameBaseDetail: newDetail } });
        },
        * getProductInto({ payload }, { put, call, select }) {
            try {
                let { gamePrizeSetDetail, mapAddress, gamePrizeSetDetailList } = yield select(state => state[tmpModule.namespace])
                const { data, success, message } = yield call(getProductInto, payload)
                if (success) {
                    if (data) {
                        let p = [{
                            mapAddress: data.mapAddress,
                            province: data.province,
                            provinceName: data.provinceName,
                            productName: data.name && data.name != "" ? data.name : data.productName,
                            latitude: data.latitude,
                            longitude: data.longitude,
                            cityName: data.cityName,
                            city: data.city,
                            productId: data.productId,
                            projectId: data.projectId,
                            estatePhone: data.estatePhone
                        }];
                        gamePrizeSetDetail.estateAddress = p;
                        if (gamePrizeSetDetailList.length > 0) {
                            for (let i = 0; i < gamePrizeSetDetailList.length; i++) {
                                gamePrizeSetDetailList[i].estateAddress = p;
                            }
                        }
                        mapAddress = data.mapAddress;
                        yield put({ type: 'updateStore', payload: { gamePrizeSetDetailList: gamePrizeSetDetailList, mapAddress: mapAddress, gamePrizeSetDetail: gamePrizeSetDetail } });
                    }

                }
            } catch (e) {}
        },
        * getLuckDrawNumConfig({ payload }, { put, call, select }) {
            try {
                let { gameLuckDrawNumConfig } = yield select(state => state[tmpModule.namespace])
                const data = yield call(luckDrawNumConfig, payload)
                if (data.success) {
                    let records = data.result.records
                    gameLuckDrawNumConfig = records
                    let dailyLogins = [],
                        developAgents = [],
                        onlineBuy = [],
                        dailyLoginChecked = false,
                        developAgentChecked  = false,
                        onlineBuyChecked = false;
                    if (records.length) {
                        records.map(item => {
                            let awardLevel = item.awardLevel
                            let awardLevels = awardLevel.split(',')
                            awardLevels.map(award => {
                                if (item.type == '1') {
                                    dailyLogins.push(`${award}等奖`)
                                    dailyLoginChecked = true
                                }
                                if (item.type == '2') {
                                    developAgents.push(`${award}等奖`)
                                    developAgentChecked = true
                                }
                                if (item.type == '3') {
                                    onlineBuy.push(`${award}等奖`)
                                    onlineBuyChecked = true
                                }
                            })
                        })
                        yield put({ type: 'updateStore', payload: { dailyLogins, developAgents, onlineBuy, gameLuckDrawNumConfig, dailyLoginChecked, developAgentChecked, onlineBuyChecked } });
                    }
                }
            } catch (e) {}
        },
    },

    // reducers: {
    //   updateStore(preState, action) {
    //     return Object.assign({}, preState, action.payload)
    //   },
    // }
    reducers: {
        updateStore(preState, action) {
            if (action.payload.panes) {
                let rewardRange = action.payload.panes.map((r) => r.title);
                action.payload.rewardRange = rewardRange
            }
            return {...preState, ...action.payload };
        }
    }
}

export default tmpModule